<?php

namespace app\service;

use app\enum\UserCode;
use app\model\User;
use library\wechat;
use Tinywan\Jwt\JwtToken;

//游戏服务
class GameService extends Base
{

    //当前分机列表
    public function login($code, $platform, $nickname, $avatar)
    {
        //获取微信小程序的openid
        switch ($platform) {
            case UserCode::PLATFORM['测试']:
                $openid = $code;
                break;
            case UserCode::PLATFORM['微信']:
                [$openid, $unionid] = (new wechat())->get_game_openid($code);
                break;
            default:
                return apiError('平台错误');
        }

        //查询会员信息
        $user = User::where(['game_openid' => $openid])->find();
        if (empty($user)) {
            if (!empty($unionid)) {
                //先查询unionid是否存在
                $user = User::where(['unionid' => $unionid])->find();

            }
            if (!empty($user)) {
                $user->game_openid = $openid;
                empty($user->nickname) && $user->nickname = $nickname;
                empty($user->avatar) && $user->avatar = $avatar;
                $user->save();
            } else {
                //注册
                $param = [
                    'game_openid' => $openid,
                    'unionid' => $unionid,
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'platform' => $platform,
                    'join_ip' => request()->header()['x-real-ip'],
                    'join_time' => date('Y-m-d H:i:s'),
                    'status' => UserCode::STATUS_NORMAL,
                ];
                //注册成功
                $user = new User();
                $user->save($param);
            }

        }
        if ($user['status'] == UserCode::STATUS_DISABLE) {
            return apiError('该账号已停用');
        }
        $user->save();

        $extend = [
            'id' => $user['id'],
            'name' => '小游戏',
            'access_exp' => 864000000,  // 100天
            'refresh_exp' => 864000000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => self::info($user)];
            return apiSuccess($data);
        }
        return apiError('失败');
    }

    public static function info(User $user)
    {
        $user->lv = 2;
        return $user;
    }


}